"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

import urllib2
import socket
from msnp.logger import Logger

    
def getPrivateIp():
    """Determines the private ipaddress of the machine.
    
    Reads the socket information
    and returns the retrieved IP address.
    
    Returns:
        The private IP address of the workstation is returned.
    """
    #TODO!!!! des gib ba mir di folsche ip zrug, k.a. brum...
#    priv_ip = None
#    tmp = socket.gethostbyname_ex(socket.gethostname())
#    if tmp != None and len(tmp)>2:
#        tmp2 = tmp[2]
#        for ip in tmp2:
#            if not ip.startswith("127"):
#                priv_ip = ip
#                break;
    #fallback if ip not found
#    if priv_ip==None:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("gmail.com",80))
    priv_ip = s.getsockname()[0]
    return priv_ip
    
def checkConnection(hosts):
    """Checks the internet connection of the workstation.
    
    Goes through a given list of hosts
    and tries to connect to them.
    
    Return:
        Returns true if it could connect to one of the hosts in the list, otherwise false. 
    """
    Logger.info("Checking internet connection:")
    for host in hosts:
        try:
            Logger.info("  -> host: '" + host.getName() + "'")
            urllib2.urlopen(host.getName(), timeout=1)
            Logger.info("     -> ok")
            return True
        except:
            Logger.info("     -> failed")
    Logger.info("No internet connection.")
    return False

